package com.ruiyi.adrobot.mongo.model.impl;


import com.ruiyi.adrobot.domain.Model;
import com.ruiyi.adrobot.domain.common.MongoPageRequest;
import com.ruiyi.adrobot.mongo.model.ModelOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by Lenovo on 2017/5/9.
 */
public class ModelRepositoryImpl implements ModelOperations {
    @Autowired
    private MongoOperations mongo;


    @Override
    public Page<Model> getListByPage(MongoPageRequest<Model> mongoPageRequest) {
        Model params = mongoPageRequest.getParams();
        Query query = new Query();
        if (StringUtils.hasText(mongoPageRequest.getSearch())) {
            Pattern pattern = Pattern.compile("^.*" + mongoPageRequest.getSearch() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("model").regex(pattern));
        }
        List<Sort.Order> orders = new ArrayList<Sort.Order>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "count"));
        Sort sort = new Sort(orders);
        mongoPageRequest.setSort(sort);
        Long count = mongo.count(query, Model.class);
        List<Model> models = mongo.find(query.with(mongoPageRequest), Model.class);
        return new PageImpl<Model>(models, mongoPageRequest, count);
    }

    @Override
    public void insertAll(List<Model> models) {
        mongo.insertAll(models);
    }
}
